<?php

class SendingsController extends AppController
{

	public $name = 'Sendings';
	public $helpers = array();
	public $uses = array('Sending', 'SendMail', 'Email');

	function beforeFilter()
	{
		parent::beforeFilter();

		$this->modelName = Inflector::singularize($this->name);
		$this->po_domain = Inflector::underscore($this->name);
		$this->url_part  = 'sending-log';
		$this->set('po_domain', $this->po_domain);
		$this->set('url_part',  $this->url_part);
		$this->set('modelName', $this->modelName);
		$this->set('PKName',    $this->{$this->modelName}->primaryKey);

		Auth::Access('active');
	}

	function list_of()
	{
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		$this->pageTitle = strip_tags(__d($po_domain, 'list_title', true));

		vendor('contingencies');
		vendor('order_html');
		vendor('pagination_html');
		vendor('page_of_data');

		$client_id = null;
		if (Auth::o()->is('client_admin')) {
    	    $auth_data = Auth::o()->data();
    	    $client_id = $auth_data['client_id'];
		}

		$contingencies = new Contingencies();
        $contingencies->model =& $this->{$modelName};
        $contingencies->expects = 'Test | Report | Candidate | ClientAdmin | Client | AuthorAdmin | AuthorClientAdmin'; // Testing | Reporting

		$author_field = "`AuthorClientAdmin`.`username`";
		if (Auth::o()->is('admin')) {
    		$author_field = "IF(`{$modelName}`.`author_admin_id` IS NULL, `AuthorClientAdmin`.`username`, `AuthorAdmin`.`username`)";
		}
		$recepient_field = "IF(`{$modelName}`.`client_admin_id` IS NULL, CONCAT(`Candidate`.`surname`, CONCAT(' ', `Candidate`.`name`)), `ClientAdmin`.`username`)";
		$type_field = $this->{$modelName}->buildFieldForOrder("`{$modelName}`.`type`", "`{$modelName}_type`", $this->{$modelName}->getTypesList());
        $contingencies->fields = array('*', $author_field." AS `{$modelName}_author`", $recepient_field." AS `{$modelName}_recepient`", $type_field);

        /////////////////////////////////////////////////////////////
        $ses_war_name = __CLASS__.':'.__FUNCTION__.':filter:1';
        if (!empty($this->data['Filter'])) {
            if (!empty($this->data['Filter']['submit_reset'])) {
                unset($_SESSION[$ses_war_name]);
                unset($this->data['Filter']);
            } elseif (!empty($this->data['Filter']['submit_apply'])) {
                $_SESSION[$ses_war_name] = $this->data['Filter'];
            }
        }
        $filter = isset($_SESSION[$ses_war_name]) ? $_SESSION[$ses_war_name] : array();
        if (!isset($filter['searche_all'])) {
        	$filter['searche_all'] = true;
        }
		if (!isset($filter['type'])) {
            $filter['type'] = 'OFFER_ON_TESTING';
        }
        if (empty($this->data['Filter'])) {
            $this->data['Filter'] = $filter;
        }
        /////////////////////////////////////////////////////////////
		$conds = array();
        if (!empty($filter['searche'])) {
            $searche_fields = array(
                "`Client`.`name`",
                "`AuthorAdmin`.`username`",
                "`AuthorClientAdmin`.`username`",
                "`ClientAdmin`.`username`",
                "`Candidate`.`surname`",
                "`Candidate`.`name`",
                "`Test`.`name`",
                "`Report`.`name`",
            );
            $searche_fields_name = array(
                "Client"            => array("name"),
                "AuthorAdmin"       => array("username"),
                "AuthorClientAdmin" => array("username"),
                "ClientAdmin"       => array("username"),
                "Candidate"         => array("surname", "name"),
                "Test"              => array("name"),
                "Report"            => array("name"),
            );
            $searche_params = array(
                'entirely'  => !empty($filter['searche_entirely']),
                'all'       => !empty($filter['searche_all']),
                'sequence'  => !empty($filter['searche_sequence']),
                'grouping'  => 'words', // chars
                'words'     => false,
            );
            $conds[] = $this->{$modelName}->searcheCond($filter['searche'], $searche_fields, $searche_params);
        }
		if (!empty($filter['from_date'])) {
			$conds[]["`{$modelName}`.`send_date`"] = ">={$filter['from_date']}";
		}
		if (!empty($filter['to_date'])) {
			$conds[]["`{$modelName}`.`send_date`"] = "<=".Date::getToDateTime($filter['to_date']);
		}
		if (!empty($filter['type'])) {
			$conds[]["`{$modelName}`.`type`"] = $filter['type'];
		}
		if (Auth::o()->is('admin')) {
    		if (!empty($filter['client_id'])) {
    			$client_id = $filter['client_id'];
    		}
		}
		if (isset($client_id)) {
			$conds[]["`{$modelName}`.`client_id`"] = $client_id;
		}
		$contingencies->conditions =& $conds;
		////////////////////////////////////////////////////////////////////////


        $appearence = new OrderHTML();
        $appearence->orderFields = array(
            $PKName => "`{$modelName}`.`{$PKName}`",
            'send_date' => "`{$modelName}`.`send_date`",
            'report' => "`Report`.`name`",
            'test' => "`Test`.`name`",
            'type' => "`{$modelName}_type`",
            'client' => "`Client`.`name`",
            'recepient' => "`{$modelName}_recepient`",
            'author' => "`{$modelName}_author`",
        );
        $appearence->defaultOrder = Order::parseString('~send_date');
        $appearence->processParams();

        $pagination = new PaginationHTML();
        $pagination->defaultLimit = 20;
        $pagination->processParams();

        $list = new PageOfData($contingencies, $appearence, $pagination);

        if (!empty($filter['searche'])) {
            foreach ($list->rows as &$row) {
                foreach ($searche_fields_name as $_model_name => $_fields) {
                	$this->{$modelName}->hightlightSearche($row[$_model_name], $filter['searche'], $_fields, $searche_params);
                }
            }
        }

        $Email =& $this->{$modelName}->getModel('Email'); /* @var $Email Email */
        $Email->rel();
        $in_queue_messages = $Email->findCount();
        $this->set('types_list', $this->{$modelName}->getTypesList());
		$this->set('clients_list', $this->{$modelName}->Client->generateList());
		$this->set('in_queue_messages', $in_queue_messages);

		$this->set('list', $list);
	}

    function view_body()
    {
        $modelName = $this->modelName;
        $PKName    = $this->{$modelName}->primaryKey;
        $po_domain = $this->po_domain;
        $url_part  = $this->url_part;

		if (!empty($this->data[$modelName]['submit_back'])) {
            $this->redirect("/{$url_part}/", null, true);
            exit();
	    }
		$this->pageTitle = strip_tags(__d($po_domain, 'details_title', true));

		$id = null;
	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
	    }

        $conds = array();
        $conds[]["`{$modelName}`.`{$PKName}`"] = $id;
        if (Auth::o()->is('client_admin')) {
            $auth_data =& Auth::o()->data();
            $conds[]["`{$modelName}`.`client_id`"] = $auth_data["client_id"];
        }
        $this->{$modelName}->rel();
	    $tmp = $this->{$modelName}->find($conds);

		if (! is_array($tmp) || !count($tmp)) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/", null, true);
			exit();
		}

		////// MENU ///////////////////////

	    $this->MainMenu->setActive($this->MainMenu->findItem("/{$url_part}/"));

		///////////////////////////////////

		$this->data = $tmp;
    }

}

?>